package com.meida.module.virbox.provider.tokenProvider.jwt;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * <b>功能名：JwtTest1</b><br>
 * <b>说明：</b><br>
 * <b>著作权：</b> Copyright (C) 2021 HUIFANEDU  CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2022-02-14 jiabing
 */
public class JwtTest1 {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException,Exception {
        JwtTest1.paseJWT("36XW7SS55GD4D3NDG1HDFGS4887SVTJGc2RHVmtYMS9YV1JnRnZ2QUdDTWdNekZNZFdVNWg0OTIrZjVYanpqTT0","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJxekNvdW50IjoxLCJ1c2VyQ291bnQiOjAsImNhdGVnb3J5Q291bnQiOjAsImNhdGVnb3J5QWN0Q291bnQiOjAsImNvbXBhbnlDb3VudCI6MCwiYXV0aFRpbWUiOiIwIiwib25saW5lQ291bnQiOjAsImV4cGlyZWRUaW1lIjoiMTY0NDgzMTgyMyJ9.Ta4QckQzUQxj0DPMv5TzSxgbWGuyIrHSQvLUJuBYAFo");
    }
    // java HMacsha256
    private static final  String MAC_INSTANCE_NAME = "HMacSHA256";

    public static String Hmacsha256(String secret, String message) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac hmac_sha256 = Mac.getInstance(MAC_INSTANCE_NAME);
        SecretKeySpec key = new SecretKeySpec(secret.getBytes(), MAC_INSTANCE_NAME);
        hmac_sha256.init(key);
        byte[] buff = hmac_sha256.doFinal(message.getBytes());
        return Base64.encodeBase64URLSafeString(buff);
    }

    // java jwt
    public static void testJWT() throws InvalidKeyException, NoSuchAlgorithmException {
        String secret = "eerp";
        String header = "{\"type\":\"JWT\",\"alg\":\"HS256\"}";
        String claim = "{\"iss\":\"cnooc\", \"sub\":\"yrm\", \"username\":\"yrm\", \"admin\":true}";

        String base64Header = Base64.encodeBase64URLSafeString(header.getBytes());
        String base64Claim = Base64.encodeBase64URLSafeString(claim.getBytes());
        String signature = JwtTest1.Hmacsha256(secret, base64Header + "." + base64Claim);

        String jwt = base64Header + "." + base64Claim  + "." + signature;
        System.out.println(jwt);
    }

    public static void paseJWT(String sec,String jwt)throws Exception{
        String header = jwt.split("\\.")[0];
        String claim = jwt.split("\\.")[1];
        String signature = jwt.split("\\.")[2];
        String parseHeader = new String(Base64.decodeBase64(header));
        System.out.println(parseHeader);
        String parseClaim = new String(Base64.decodeBase64(claim));
        System.out.println(parseClaim);
        String parseSign = JwtTest1.Hmacsha256(sec,header+"."+claim);
        System.out.println(signature);
        System.out.println(parseSign);
    }
}   